from turtledemo.penrose import start

from flask import Blueprint, render_template, jsonify, request, session, redirect, url_for
from select import select

# from soupsieve import select

from utils.util import ArticleUtil

from utils.database_util import query_data

from user_center import login
article_read = Blueprint('article_read', __name__)

@article_read.route('/article_read')
def article_read_view():
    return render_template('article_read.html')

@article_read.route('/article/list', methods=['GET', 'POST'])
def article_list():
    sql_str = "select article.*, users.nickname from article left join users on users.userid = article.userid order by article.updatetime desc limit 10"
    result = query_data(sql_str)
    result = ArticleUtil.transfrom_article(result)
    if len(result):
        return jsonify({'code':1, 'info':result})
    else:
        return jsonify({'code':0, 'info':[]})

@article_read.route('/article/list/<int:page>',methods=['GET','POST'])
def article_list_limit(page):

    sql = 'select count(articleid) as `article_number` from article'
    select_sql ='select article.*, users.nickname from article left join users on users.userid = article.userid order by article.updatetime desc limit {},{}'
    keyword = request.form.get("keyword")
    if keyword is not None:
        sql = 'select count(articleid) as `article_number` from article where headline like "%'+keyword+'%"'
        select_sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid where headline like "%'+keyword+'%" order by article.updatetime desc limit {},{}'
        keyword = request.form.get("keyword")
        print(keyword)
    number = 10
    result = query_data(sql)
    count = result[0]['article_number']
    max_page = int(count / number) + 1
    start = (page - 1) * number
    end = start + number
    print('start: ',start)
    print('end: ',end)
    sql_str = select_sql.format(start, 10)
    print(sql_str)
    result = query_data(sql_str)
    result = ArticleUtil.transfrom_article(result)
    if len(result):
        return jsonify({'code': 1,'info': result, 'page':{'max_page':max_page, 'now_page':page}})
    else:
        return jsonify({'code':0,'info':[]})

@article_read.route('/article/<int:article_id>',methods=['GET','POST'])
def article_info2(article_id):
    sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid where articleid = %d' % article_id
    result = query_data(sql)
    result = ArticleUtil.transfrom_article(result)
    if len(result) == 0:
        return render_template("error-404.html")
    else:
        read_sql = 'update article set readcount = {} where articleid={}'.format(result[0]['readcount']+1, article_id)
        query_data(read_sql)
        userid = session.get('userid')
        if userid is None:
            # return render_template("login.html")
            login()
            return redirect(url_for('user_center.login'))
        credit(userid, article_id)
        # return render_template("article_info.html", article=result[0])
        return render_template("article_read.html", article=result[0])

        # return 'no'
def credit(user_id, article_id):
    sql = 'select * from article where articleid = %d' % article_id
    articles = query_data(sql)
    article = articles[0] if len(articles) == 1 else None
    if user_id != article['userid']:
        article_credit = select_article_credit(article_id)
        user_credit = select_user_credit(user_id)
        if user_credit > article_credit:
            if is_buy(user_id, article_id):
                return True
            update_user_credit(user_id, (user_credit - article_credit), article_credit, "阅读文章扣除积分",article_id)
            author_id = article['userid']
            author_credit = select_user_credit(author_id)
            update_user_credit(author_id, (author_credit + article_credit), article_credit, "文章被阅读获得积分", article_id)
            return True
        else:
            return False
    else:
        return True

def select_user_credit(userid):
        sql = 'select * from users where userid = %d' % userid
        user_info = query_data(sql)
        return user_info[0]["credit"]

def select_article_credit(article_id):
    sql = 'select * from article where articleid=%d' % article_id
    articles = query_data(sql)
    return articles[0]["credit"]

def update_user_credit(user_id, credit, number, type, article_id):
    sql = 'update users set credit = {} where userid = {}'.format(credit, user_id)
    query_data(sql)
    sql2 = "INSERT INTO `credit` (`userid`, `category`, `target`, `credit`) VALUES (%d, '%s', %d, %d)" % (user_id, type, article_id, number)
    query_data(sql2)
    print(user_id, " : ", credit)

def is_buy(user_id, article_id):
    sql = 'select * from credit where userid=%d and target=%d' % (user_id, article_id)
    result = query_data(sql)
    return len(result) > 0